package com.ssl.basics.thread.incre;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述：
 *
 * @author ssl
 * @create 2021/7/13 0013.
 */
public class ThreadIncreDemo3 {
    static class ValueEntity {
        private int sum;
        private Lock lock = new ReentrantLock();

        public void incre() {
            lock.lock();
            try {
                sum++;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        int threadSize = 10;
        ValueEntity entity = new ValueEntity();
        CountDownLatch latch = new CountDownLatch(threadSize);
        for (int i = 0; i < threadSize; i++) {
            new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    entity.incre();
                }
                latch.countDown();
            }, String.valueOf(i)).start();
        }
        latch.await();
        System.out.println(entity.sum);
    }
}
